package org.vincen.helloworld.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo2 extends ServerSocket {

	private static final int SERVER_PORT = 8021;

	public ServerDemo2() throws IOException {
		super(SERVER_PORT);

		try {
			while (true) {
				Socket socket = accept();
				new CreateServerThread(socket);
			}
		} catch (IOException e) {
		} finally {
			close();
		}
	}

	// --- CreateServerThread
	class CreateServerThread extends Thread {
		private Socket client;
		private BufferedReader in;
		private PrintWriter out;

		public CreateServerThread(Socket s) throws IOException {
			client = s;
			in = new BufferedReader(new InputStreamReader(
					client.getInputStream()));
			out = new PrintWriter(client.getOutputStream(), true);
			out.println("--- Welcome ---");
			start();
		}

		public void run() {
			try {
				String line = in.readLine();

				while (line != null) {
//				while (line.contains("bye")){
					// 处理客户端的内容，并返回给客户端回执
					String msg = createMessage(line);
					out.println(msg);
					System.out.println(line);
					line = in.readLine();
				}
				out.println("--- See you, bye! ---");
				System.out.println("--- See you, bye! ---");
				client.close();
			} catch (IOException e) {
			}
		}

		// 处理客户端发来的内容，并给出返回
		private String createMessage(String line) {
			return "You send :" + line;
		}
	}

	@SuppressWarnings("resource")
	public static void main(String[] args) throws IOException {
		new ServerDemo2();
	}

}
